package com.chapter.sample.answer.multiplex;


import lombok.Data;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

@Data
class Tsl {

    private int saleTotal;

    public synchronized void saleTotals() {
        saleTotal++;
    }

    ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

    public synchronized void saleThreadLocalTotals() {
        threadLocal.set(threadLocal.get() + 1);
    }
}

public class ThreadLocalDemoV1 {
    public static void main(String[] args) throws InterruptedException {
        Tsl tsl = new Tsl();
        CountDownLatch countDownLatch = new CountDownLatch(3);
        for (int i = 1; i <= 3; i++) {
            new Thread(() -> {
                try {
                    for (int j = 1; j <= new Random().nextInt(6) + 1; j++) {
                        tsl.saleTotals();
                        tsl.saleThreadLocalTotals();
                    }
                    System.out.println(Thread.currentThread().getName() + "销售，卖出：" + tsl.threadLocal.get());
                } finally {
                    countDownLatch.countDown();
                    tsl.threadLocal.remove();
                }
            }, String.valueOf(i)).start();
        }
        countDownLatch.await();
        System.out.println(tsl.getSaleTotal());
    }
}

